package com.eb.controller;

import com.eb.result.Result;
import com.eb.util.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口，文件上传
 */
@RestController
@RequestMapping("/common")
@Api(tags = "通用接口")
@Slf4j
@CrossOrigin
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(@RequestParam("file") MultipartFile file)
    {
        log.info("文件上传：{}",file);
        try {
            //原始文件重命名+UUID，防止冲突
            String originalName = file.getOriginalFilename();
            //截取后缀
            String extension = originalName.substring(originalName.lastIndexOf("."));
            String objName = UUID.randomUUID() + extension;
            String filepath = aliOssUtil.upload(file.getBytes(), objName);
            return Result.success(filepath);
        }catch (IOException e)
        {
            log.error("文件上传失败 {}",e);
        }

        return null;
    }
}
